package com.chinabank.web.controller;

import java.text.ParseException;
import java.util.Enumeration;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;

import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

import com.chinabank.exception.NoSuchAccountException;
import com.chinabank.model.Account;
import com.chinabank.service.AccountService;


@Controller
@RequestMapping("/login.do")
public class LoginController {

	private AccountService accountService;

	public AccountService getAccountService() {
		return accountService;
	}

	@Resource
	public void setAccountService(AccountService accountService) {
		this.accountService = accountService;
	}

	@RequestMapping(method = RequestMethod.GET)
	public String displayLoginForm(HttpServletRequest request, ModelMap model)
			throws ParseException {
		return "forward:/public/login.jsp";
	}

	// params = "method=login",
	@RequestMapping(method = RequestMethod.POST)
	public String login(HttpServletRequest request, ModelMap model) {
		String username = request.getParameter("username");
		String password = request.getParameter("password");
		Account account;
		try {
			account = accountService.getAccount(username, password);
			request.getSession().setAttribute("account", account);
			request.getSession().setAttribute("permission",
					account.getMyGroup().getPermissions());
			return "redirect:/admin/home.do";
		} catch (NoSuchAccountException e) {
			model.put("error", "用户名或者密码错误");
			return "login";
		}
	}
}
